import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

Rectangle {
    id: chartContainer
    color: "white"
    radius: 10
    border.color: "#e0e0e0"
    border.width: 1
    
    ColumnLayout {
        anchors.fill: parent
        anchors.margins: 15
        spacing: 10
        
        // 标题
        Text {
            text: "信号质量趋势 (最近1小时)"
            font.pixelSize: 18
            font.bold: true
            color: "#2c3e50"
        }
        
        // 图表区域
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "#fafafa"
            radius: 8
            border.color: "#e0e0e0"
            border.width: 1
            
            Canvas {
                id: chartCanvas
                anchors.fill: parent
                anchors.leftMargin: 60  // 增加左边距以显示完整Y轴标签
                anchors.rightMargin: 80  // 增加右边距以显示完整数值
                anchors.topMargin: 20
                anchors.bottomMargin: 60  // 为时间标签留出更多空间
                
                Timer {
                    interval: 2000
                    running: true
                    repeat: true
                    onTriggered: chartCanvas.requestPaint()
                }
                
                // 监听平均信号质量变化，立即更新颜色
                Connections {
                    target: networkMonitor
                    function onAvgSignalQualityChanged() {
                        chartCanvas.requestPaint()
                    }
                }
                
                // 根据信号质量获取线条颜色
                function getQualityColor(quality) {
                    if (quality >= 80) {
                        return "#27ae60"  // 绿色 - 优秀
                    } else if (quality >= 60) {
                        return "#f39c12"  // 橙色 - 良好
                    } else {
                        return "#e74c3c"  // 红色 - 较差
                    }
                }
                
                // 根据信号质量获取填充颜色渐变
                function getQualityFillColor(quality) {
                    if (quality >= 80) {
                        return {
                            start: "rgba(39, 174, 96, 0.3)",   // 绿色渐变
                            end: "rgba(39, 174, 96, 0.05)"
                        }
                    } else if (quality >= 60) {
                        return {
                            start: "rgba(243, 156, 18, 0.3)",  // 橙色渐变
                            end: "rgba(243, 156, 18, 0.05)"
                        }
                    } else {
                        return {
                            start: "rgba(231, 76, 60, 0.3)",   // 红色渐变
                            end: "rgba(231, 76, 60, 0.05)"
                        }
                    }
                }
                
                onPaint: {
                    var ctx = getContext("2d")
                    ctx.clearRect(0, 0, width, height)
                    
                    // 获取数据
                    var data = networkMonitor.getSignalTrendData()
                    if (data.length === 0) return
                    
                    var maxY = 100
                    var minY = 0
                    var rangeY = maxY - minY
                    
                    // 获取当前平均信号质量来确定颜色
                    var avgQuality = networkMonitor.avgSignalQuality
                    var lineColor = getQualityColor(avgQuality)
                    var fillColor = getQualityFillColor(avgQuality)
                    
                    // 调试信息：显示当前信号质量和对应颜色
                    // console.log("当前平均信号质量:", avgQuality.toFixed(1) + "%", "颜色:", lineColor)
                    
                    // 绘制坐标轴
                    // Y轴主线
                    ctx.strokeStyle = "#95a5a6"
                    ctx.lineWidth = 2
                    ctx.beginPath()
                    ctx.moveTo(0, 0)
                    ctx.lineTo(0, height)
                    ctx.stroke()
                    
                    // X轴主线
                    ctx.strokeStyle = "#95a5a6"
                    ctx.lineWidth = 2
                    ctx.beginPath()
                    ctx.moveTo(0, height)
                    ctx.lineTo(width, height)
                    ctx.stroke()
                    
                    // 绘制网格线和标签
                    ctx.strokeStyle = "#e0e0e0"
                    ctx.lineWidth = 1
                    ctx.font = "11px sans-serif"
                    ctx.fillStyle = "#7f8c8d"
                    
                    // Y轴网格线和刻度标签
                    for (var i = 0; i <= 5; i++) {
                        var y = (height / 5) * i
                        var value = maxY - (rangeY / 5) * i
                        
                        // 绘制水平网格线
                        ctx.strokeStyle = "#e0e0e0"
                        ctx.lineWidth = 1
                        ctx.beginPath()
                        ctx.moveTo(0, y)
                        ctx.lineTo(width, y)
                        ctx.stroke()
                        
                        // 绘制Y轴刻度线
                        ctx.strokeStyle = "#bdc3c7"
                        ctx.lineWidth = 1
                        ctx.beginPath()
                        ctx.moveTo(-5, y)
                        ctx.lineTo(0, y)
                        ctx.stroke()
                        
                        // 绘制刻度标签
                        ctx.fillStyle = "#7f8c8d"
                        ctx.font = "12px sans-serif"
                        ctx.textAlign = "right"
                        ctx.textBaseline = "middle"
                        ctx.fillText(value.toFixed(0) + "%", -12, y)
                    }
                    
                    // X轴时间标签和刻度
                    var currentTime = new Date()
                    for (var i = 0; i <= 4; i++) {
                        var x = (width / 4) * i
                        var timeOffset = (4 - i) * 2.5 // 每2.5分钟一个标签(10分钟/4)
                        var labelTime = new Date(currentTime.getTime() - timeOffset * 60000)
                        var timeLabel = Qt.formatTime(labelTime, "HH:mm")
                        
                        // 绘制垂直网格线（淡色）
                        ctx.strokeStyle = "#f5f5f5"
                        ctx.lineWidth = 1
                        ctx.beginPath()
                        ctx.moveTo(x, 0)
                        ctx.lineTo(x, height)
                        ctx.stroke()
                        
                        // 绘制X轴刻度线
                        ctx.strokeStyle = "#bdc3c7"
                        ctx.lineWidth = 1
                        ctx.beginPath()
                        ctx.moveTo(x, height)
                        ctx.lineTo(x, height + 5)
                        ctx.stroke()
                        
                        // 绘制时间标签
                        ctx.fillStyle = "#7f8c8d"
                        ctx.font = "11px sans-serif"
                        ctx.textAlign = "center"
                        ctx.textBaseline = "top"
                        ctx.fillText(timeLabel, x, height + 8)
                    }
                    
                    // 绘制区域填充
                    if (data.length > 0) {
                        var gradient = ctx.createLinearGradient(0, 0, 0, height)
                        gradient.addColorStop(0, fillColor.start)
                        gradient.addColorStop(1, fillColor.end)
                        
                        ctx.beginPath()
                        ctx.moveTo(0, height)
                        
                        for (var i = 0; i < data.length; i++) {
                            var x = (width / (data.length - 1)) * i
                            var y = height - ((data[i].y - minY) / rangeY) * height
                            
                            if (i === 0) {
                                ctx.lineTo(x, y)
                            } else {
                                ctx.lineTo(x, y)
                            }
                        }
                        
                        ctx.lineTo(width, height)
                        ctx.closePath()
                        ctx.fillStyle = gradient
                        ctx.fill()
                    }
                    
                    // 绘制分段彩色折线
                    if (data.length > 0) {
                        ctx.lineWidth = 3
                        ctx.lineJoin = "round"
                        
                        for (var i = 0; i < data.length - 1; i++) {
                            var x1 = (width / (data.length - 1)) * i
                            var y1 = height - ((data[i].y - minY) / rangeY) * height
                            var x2 = (width / (data.length - 1)) * (i + 1)
                            var y2 = height - ((data[i + 1].y - minY) / rangeY) * height
                            
                            // 使用当前点和下一点的平均质量来确定线段颜色
                            var avgSegmentQuality = (data[i].y + data[i + 1].y) / 2
                            var segmentColor = getQualityColor(avgSegmentQuality)
                            
                            ctx.beginPath()
                            ctx.strokeStyle = segmentColor
                            ctx.moveTo(x1, y1)
                            ctx.lineTo(x2, y2)
                            ctx.stroke()
                        }
                        
                        // 绘制数据点（每个点根据自身质量值设置颜色）
                        for (var i = 0; i < data.length; i++) {
                            if (i % 5 === 0 || i === data.length - 1) {
                                var x = (width / (data.length - 1)) * i
                                var y = height - ((data[i].y - minY) / rangeY) * height
                                
                                // 根据该点的信号质量值获取颜色
                                var pointQuality = data[i].y
                                var pointColor = getQualityColor(pointQuality)
                                
                                ctx.beginPath()
                                ctx.arc(x, y, 4, 0, Math.PI * 2)
                                ctx.fillStyle = pointColor
                                ctx.fill()
                                ctx.strokeStyle = "white"
                                ctx.lineWidth = 2
                                ctx.stroke()
                            }
                        }
                        
                        // 绘制最后一个点的值（使用该点的颜色）
                        var lastX = (width / (data.length - 1)) * (data.length - 1)
                        var lastY = height - ((data[data.length - 1].y - minY) / rangeY) * height
                        var lastPointQuality = data[data.length - 1].y
                        var lastPointColor = getQualityColor(lastPointQuality)
                        
                        ctx.font = "bold 14px sans-serif"
                        ctx.fillStyle = lastPointColor
                        ctx.textAlign = "left"
                        ctx.fillText(lastPointQuality.toFixed(1) + "%", lastX - 40, lastY + 10)
                    }
                }
            }
            
            // Y轴标签
            Text {
                x: 5
                y: parent.height / 2 - height / 2
                text: "信号质量 (%)"
                font.pixelSize: 11
                color: "#7f8c8d"
                rotation: -90
                transformOrigin: Item.Center
            }
            
            // X轴标签
            Text {
                anchors.horizontalCenter: parent.horizontalCenter
                y: parent.height - 15
                text: "时间 (最近10分钟)"
                font.pixelSize: 11
                color: "#7f8c8d"
            }
            
            // 状态指示
            Row {
                anchors.right: parent.right
                anchors.top: parent.top
                anchors.margins: 10
                spacing: 15
                
                Rectangle {
                    width: 70
                    height: 25
                    radius: 12
                    color: "#27ae60"
                    opacity: networkMonitor.avgSignalQuality >= 80 ? 1.0 : 0.6
                    
                    Text {
                        anchors.centerIn: parent
                        text: "优秀≥80%"
                        font.pixelSize: 10
                        color: "white"
                        font.bold: true
                    }
                }
                
                Rectangle {
                    width: 70
                    height: 25
                    radius: 12
                    color: "#f39c12"
                    opacity: (networkMonitor.avgSignalQuality >= 60 && networkMonitor.avgSignalQuality < 80) ? 1.0 : 0.6
                    
                    Text {
                        anchors.centerIn: parent
                        text: "良好60-79%"
                        font.pixelSize: 9
                        color: "white"
                        font.bold: true
                    }
                }
                
                Rectangle {
                    width: 70
                    height: 25
                    radius: 12
                    color: "#e74c3c"
                    opacity: networkMonitor.avgSignalQuality < 60 ? 1.0 : 0.6
                    
                    Text {
                        anchors.centerIn: parent
                        text: "较差<60%"
                        font.pixelSize: 10
                        color: "white"
                        font.bold: true
                    }
                }
            }
        }
    }
}

